import $store from '@/store/index.js';
import msgSqlite from "@/sqlite_services/msg.js"
// 节流操作变量
let msgQueue = [];


// 处理函数
const handle = (data) => {
	console.log('私聊--------',data);
  // 将消息加入队列
  msgQueue.push(data);
  // 调用节流后的处理函数 200秒内接收统一处理
  uni.$u.throttle(processQueue, 200, false,'private')
}
// 处理消息队列的函数
const processQueue = async () => {
  const messagesToHandle = [...msgQueue];
  msgQueue = [];
  console.log('messagesToHandle-----',messagesToHandle);
  if (messagesToHandle.length === 0) return;
  // 避免后台推送相同的消息----根据 msg_id 去重
  console.log('去重来了');
  const uniqueArray = Array.from(new Map(messagesToHandle.map(item => [item.msg_id, item])).values());
  console.log('messagesToHandle2-----',uniqueArray);
  try {
	let myId = $store.state.user.user_info.user_id; // 获取当前用户ID
	
	// 按对话对象分组消息
	let groupedMessages = uniqueArray.reduce((groups, data) => {
		let conversationId = data.sender_id == myId ? data.target_id : data.sender_id;
		if (!groups[conversationId]) {
		  groups[conversationId] = [];
		}
		groups[conversationId].push(data);
	    return groups;
	}, {});
    for (let conversationId in groupedMessages) {
          let msgList = groupedMessages[conversationId];
    
          // 提取所有消息ID和本地ID，并确保每个ID都是字符串格式
          let ids = msgList.flatMap(item => [`${item.msg_id}`, `${item.local_id}`].filter(id => id && id != '0'));
    
          // 为每个ID添加引号，以便在SQL查询中正确处理
          let quotedIds = ids.map(id => `"${id}"`).join(',');
    
          // 批量查询现有消息
          let existingMessages = await $store.state.user.sqlite.message.where([
            { field: 'msg_id', val: `(${quotedIds})`, opt: 'IN' }
          ]).get();
			console.log(existingMessages);
          // 使用Set存储已存在的消息ID
          let existingMsgIds = new Set(existingMessages.map(msg => msg.msg_id));
		  
          // 筛选需要插入的新消息
          let newMessages = msgList.filter(item =>
            !existingMsgIds.has(item.msg_id) && !existingMsgIds.has(item.local_id)
          ).map(item => ({
            msg_id: item.msg_id,
            local_id: (item.local_id && item.local_id != '0') ? item.local_id : item.msg_id,
            sender_id: item.sender_id,
            target_id: item.target_id,
            create_time: item.create_time,
            msg_type: item.msg_type,
			ip:item.ip || '',
			ip_addr:item.ip_addr || '',
            conversation_id: item.conversation_id,
			ref_msg_id:item.ref_msg_id || '0',
            chat_type: item.chat_type,
            msg_status: 'unread',
            content_text: item.content_text
          }));
		  
		  
		  
          if (newMessages.length > 0) {
			  console.log('newMessages-----',newMessages);
			  try{
			  	await msgSqlite.newMsg(newMessages, true);
				const filteredMessages = newMessages.filter(message => message.sender_id != myId).map(message => message.msg_id);
				if(filteredMessages.length)uni.$api.chat.received_receipt({msg_ids:filteredMessages})
			  }catch(e){
			  	console.error(e);
			  }
          }
        }
  } catch (e) {
    console.error(e);
  }
}

// //私聊消息
// const handle = async(data)=>{
// 	try{
// 		let msgsql = await $store.state.user.sqlite.message.where([{
// 				field: 'msg_id',
// 				val: `'${data.msg_id}'`,
// 				logic: 'OR'
// 			},
// 			{
// 				field: 'msg_id',
// 				val: `'${data.local_id}'`,
// 				logic: 'OR'
// 			}
// 		]).first()
// 		if(!msgsql){
// 			let n_msg = {
// 				msg_id: data.msg_id,
// 				local_id: (!data.local_id || data.local_id == '0') || data.msg_id,
// 				sender_id: data.sender_id,
// 				target_id: data.target_id,
// 				create_time: data.create_time,
// 				msg_type: data.msg_type,
// 				conversation_id:data.conversation_id,
// 				chat_type: data.chat_type,
// 				msg_status:'unread',
// 				content_text: data.content_text
// 			}
// 			await msgSqlite.newMsg(n_msg,true)
// 		}
// 	}catch(e){
		
// 	}
// }
export default handle